﻿using System;
using System.Web;
using System.Web.Security;
using TeamsPortal.Configuration;
using TeamsPortal.Web.State;
using TeamsPortal.ServiceClient;
using TeamsPortal.DataAccess;

namespace TeamsPortal.Web.Controllers.Helpers
{
    /// <summary>
    /// Helper for providers authentication. Required HttpContext.
    /// </summary>
    public static class SecurityHelper
    {
		/// <summary>
		/// If enabled by configuration, tries to login the current membership user (reading cookie / identity) as portals user
		/// </summary>
		public static bool TryFinishMembershipLogin(HttpContextBase context, SessionWrapper session, IUsersServiceClient usersServiceClient)
		{
			if (SiteConfiguration.Current.AuthenticationProviders.FormsAuth.IsDefined && (!String.IsNullOrEmpty(context.User.Identity.Name)))
			{
                return TryFinishMembershipLogin(session, Membership.GetUser(), usersServiceClient);
			}
			else
			{
				return false;
			}
		}
		/// <summary>
		/// Logs the user in or creates the a site user account if the user does not exist, based on membership user.
		/// Sets the logged user in the session.
		/// </summary>
		/// <exception cref="ValidationException"></exception>
        public static bool TryFinishMembershipLogin(SessionWrapper session, MembershipUser membershipUser, IUsersServiceClient usersServiceClient)
        {
            bool logged = false;

            if (membershipUser != null)
            {
                User siteUser = usersServiceClient.GetByProviderId(AuthenticationProvider.Membership, membershipUser.ProviderUserKey.ToString());
                session.User = new UserState(siteUser, AuthenticationProvider.Membership);
				logged = true;
            }

            return logged;
        }
	}
}
